package com.example.springboot1.utils;

import com.example.springboot1.entity.Zone;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ckj
 * @description TODO
 * @date 2022-08-11 11:03
 */


public class TreeUtils {


    public static List<Zone> buildTree3(List<Zone> zoneList) {
        Map<String, List<Zone>> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(Zone::getParentId));
        zoneList.forEach(zone -> zone.setChildren(zoneByParentIdMap.get(zone.getId())));
        return zoneList.stream().filter(v -> v.getParentId().equals("0")).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<Zone> zoneList = new ArrayList<>();
        zoneList.add(new Zone("1", "上海", "0"));
        zoneList.add(new Zone("2", "北京", "0"));
        zoneList.add(new Zone("3", "河南", "0"));
        zoneList.add(new Zone("31", "郑州", "3"));
        zoneList.add(new Zone("32", "洛阳", "3"));
        zoneList.add(new Zone("321", "洛龙", "32"));
        zoneList.add(new Zone("11", "松江", "1"));
        zoneList.add(new Zone("111", "泗泾", "11"));
        // 测试第三种方法
        List<Zone> rootZone3 = buildTree3(zoneList);
        System.out.println("");
    }
}
